//
//  confrimOrderVc.m
//  MJApp
//
//  Created by John on 15/3/30.
//  Copyright (c) 2015年 wangliang. All rights reserved.
//

#import "confrimOrderVc.h"
#import "CORecivePersonInfoCell.h"
#import "COShopInfoCell.h"
#import "ProductBuyNumCell.h"
#import "COSendWayCell.h"
#import "COUserIntegralCell.h"
#import "COUseMoneyCell.h"
#import "COChosePayWayCell.h"
#import "COPayWayCell.h"
#import "COSendWayCell.h"
#import "SelectAddressViewController.h"
#import "MineOrderViewController.h"

@interface confrimOrderVc ()<UITableViewDataSource,UITableViewDelegate,CellProtocol>
{
    BOOL isWeiXin;//1 为微信支付 0 为支付宝支付
}
@property(nonatomic,strong)NSDictionary *productDic;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)NSDictionary *addressDic;
@property(nonatomic,strong)NSDictionary *userMoenyDic;
@property(nonatomic,strong)ProductBuyNumCell *numcell;

@end

@implementation confrimOrderVc

- (instancetype)initWithDic:(NSDictionary *)dic {
    
    if (self = [super init]) {
        
        self.productDic = dic;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"确认订单";
    // Do any additional setup after loading the view from its nib.
    [self obationData];
    [self obationMoeny];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAddress:) name:@"selectAddress" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)obationData {
    
    NSDictionary *dic = @{@"user_id":[userInfoTool share].ID};
    [WLHttpRequestAfter userGetUserAddressWithParam:dic usingSucessBlock:^(BOOL isSucess, NSDictionary *resultDictionary) {
        
        if (resultDictionary) {
            
            NSArray *addrList = resultDictionary[@"data"];
            for (NSDictionary *dic in addrList) {
                
                if ([dic[@"defaultAddress"] intValue] == 1) {
                    self.addressDic = dic;
                    break;
                }
            }
        }
        [self.tableView reloadData];
        
    } andFailureBlock:^(NSError *resultError) {
        
    }];
}

- (void)obationMoeny {
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"user_id"] = [userInfoTool share].ID;
    [WLHttpRequestAfter userGetMyWalletWithParam:dic usingSucessBlock:^(BOOL isSucess, NSDictionary *resultDictionary) {
        
        if ([resultDictionary[@"status"] intValue] == 1) {
            
            self.userMoenyDic = resultDictionary[@"data"];
            [self.tableView reloadData];
        }
        
    } andFailureBlock:^(NSError *resultError) {
        
    }];
}

- (IBAction)confrirmOrder:(id)sender {
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 9;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    return 20;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    DSXTableViewCell * cell = (DSXTableViewCell * )[self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.cellH;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    switch (indexPath.row) {
        case 0:
        {
            CORecivePersonInfoCell * cell = [CORecivePersonInfoCell cellForTableview:tableView];
            if (self.addressDic != nil) {
                cell.infoDic = self.addressDic;
            }
            return cell;
            break;
        }
        case 1:
        {
            COShopInfoCell * cell = [COShopInfoCell cellForTableview:tableView];
            cell.infoDic = self.productDic;
            return cell;
            break;
        }
        case 2:
        {
            ProductBuyNumCell * cell = [ProductBuyNumCell cellForTableview:tableView];
            cell.currNum = [self.productDic[@"num"] integerValue];
            self.numcell = cell;
            return cell;
            break;
        }
        case 3:
        {
            COSendWayCell * cell = [COSendWayCell cellForTableview:tableView];
            return cell;
            break;
        }
        case 4:
        {
            COUserIntegralCell * cell = [COUserIntegralCell cellForTableview:tableView];
            if (self.userMoenyDic) {
                
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                dic[@"integ"] = self.userMoenyDic[@"integrate"];
                cell.infoDic = dic;
            }
           
            return cell;
            break;
        }
        case 5:
        {
            COUseMoneyCell * cell = [COUseMoneyCell cellForTableview:tableView];
            
            if (self.userMoenyDic) {
                
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                dic[@"money"] = self.userMoenyDic[@"money"];
                cell.infoDic = dic;
            }
            
            return cell;
            break;
        }
        case 6:
        {
            COChosePayWayCell * cell = [COChosePayWayCell cellForTableview:tableView];
            return cell;
            break;
        }
        case 7:
        {
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            dic[@"name"] = @"支付宝客户端";
            dic[@"desc"] = @"推荐安装支付宝客户端的用户使用";
            dic[@"pic"] = @"sczf_18";
            dic[@"isSelect"] = @(!isWeiXin);
            COPayWayCell * cell = [COPayWayCell cellForTableview:tableView];
            cell.infoDic = dic;
            cell.delegate = self;
            return cell;
            break;
        }
        case 8:
        {
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            dic[@"name"] = @"微信支付";
            dic[@"desc"] = @"推荐已开通微信支付的用户使用";
            dic[@"pic"] = @"sczf_25";
            dic[@"isSelect"] = @(isWeiXin);
            COPayWayCell * cell = [COPayWayCell cellForTableview:tableView];
            cell.infoDic = dic;
            cell.delegate = self;
            return cell;
            break;
        }
            
        default:
            return nil;
            break;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        
        SelectAddressViewController *selectAddressVC = [[SelectAddressViewController alloc] init];
        [self.navigationController pushViewController:selectAddressVC animated:YES];
    }
    
}

- (void)changeAddress:(NSNotification *)notice {
    
    self.addressDic = notice.userInfo;
    [self.tableView reloadData];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:nil name:@"selectAddress" object:nil];
}

- (IBAction)createOrder:(id)sender {
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"user_id"] = [userInfoTool share].ID;
    dic[@"cid"] = self.productDic[@"commodity_id"];
    dic[@"title"] = @"title";
    dic[@"description"] = @"description";
    dic[@"phone"] = self.addressDic[@"phone"];
    dic[@"addressId"] =self.addressDic[@"id"];
    dic[@"uname"] = self.addressDic[@"name"];
    dic[@"num"] = [NSString stringWithFormat:@"%ld",self.numcell.currNum];
    dic[@"totalPrice"] = @"100";
    dic[@"color"] = self.productDic[@"color_id"];
    dic[@"size"] = self.productDic[@"size"];
    [WLHttpRequestAfter userOrderWithParam:dic usingSucessBlock:^(BOOL isSucess, NSDictionary *resultDictionary) {
        
        if ([resultDictionary[@"status"] intValue] == 1) {
            
            if (!isWeiXin) {
                
                PayProduct *payProduct = [[PayProduct alloc] init];
                payProduct.price = @"0.01";
                payProduct.desc = resultDictionary[@"data"][@"description"];
                payProduct.orderID = resultDictionary[@"data"][@"code"];
                payProduct.name = resultDictionary[@"data"][@"title"];
                
                [WLPayModel payModelProudct:payProduct withBlock:^(NSDictionary *resultDictionary) {
                    
                    NSString * str = [NSString stringWithFormat:@"%@",resultDictionary[@"resultStatus"]];
                    if ([str isEqualToString:@"9000"]) {
                        //支付成功
                        [[DMCAlertCenter defaultCenter] postAlertWithMessage:@"支付成功"];
                        
                    }else if ([str isEqualToString:@"8000"]) {
                        //正在处理中
                        [[DMCAlertCenter defaultCenter] postAlertWithMessage:@"正在处理中"];
                    }else if ([str isEqualToString:@"6001"]) {
                        //用户中途取消
                        [[DMCAlertCenter defaultCenter] postAlertWithMessage:@"用户中途取消"];
                    }else if ([str isEqualToString:@"6002"]) {
                        //网络连接出错
                        [[DMCAlertCenter defaultCenter] postAlertWithMessage:@"网络连接出错"];
                    }
                    
                    
                    TabBarController *tab = (TabBarController *)self.tabBarController;
                    NSInteger allNum = tab.viewControllers.count;
                    [tab setIndex:allNum - 1];
                    [self.navigationController popToRootViewControllerAnimated:YES];
                    HWNavigationController *tabVC = tab.viewControllers[allNum - 1];
                    MineOrderViewController *orderVC = [[MineOrderViewController alloc] init];
                    [tabVC pushViewController:orderVC animated:YES];
                    
                    
                }];
            }else {
                
                NSMutableDictionary *orderDic = [NSMutableDictionary dictionary];
                orderDic[@"order_name"] = @"test ming jing";
                orderDic[@"order_price"] = @"1"; //分为单位
                orderDic[@"orderno"] = resultDictionary[@"data"][@"code"];
                
                payRequsestHandler *pay = [[payRequsestHandler alloc] init];
                BOOL is = [pay init:APP_ID mch_id:MCH_ID];
                [pay setKey:@"1040161xiaopoiuytrewqmnbvcxzasdf"];
                NSDictionary *dic = [pay sendPay_demo:orderDic];
                PayReq* req             = [[PayReq alloc] init];
                req.openID              = [dic objectForKey:@"appid"];
                req.partnerId           = [dic objectForKey:@"partnerid"];
                req.prepayId            = [dic objectForKey:@"prepayid"];
                req.nonceStr            = [dic objectForKey:@"noncestr"];
                NSMutableString *stamp  = [dic objectForKey:@"timestamp"];
                req.timeStamp           = stamp.intValue;
                req.package             = [dic objectForKey:@"package"];
                req.sign                = [dic objectForKey:@"sign"];
                [WXApi sendReq:req];
            }
            
            [[DMCAlertCenter defaultCenter] postAlertWithMessage:@"下单成功"];
        }
        
    } andFailureBlock:^(NSError *resultError) {
        
    }];
}


- (void)cellProtocolWithObj:(id)obj withDic:(id)dic {
    
    if ([obj isKindOfClass:[COPayWayCell class]]) {
        
        isWeiXin = [dic[@"isWeixin"] boolValue];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:7 inSection:0];
        NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:8 inSection:0];
        
        [self.tableView reloadRowsAtIndexPaths:@[indexPath,indexPath1] withRowAnimation:UITableViewRowAnimationNone];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end
